﻿

(function($) {

    $.fn.TimePlot = function(chartContainerId) {
        return this.each(function(i) {
            $('#' + chartContainerId).append('<div id="TimePlotChart' + i + '" style="height: 300px;"></div>');
            $.DrawChartForTable(this, i, 'TimePlotChart' + i);
        });
    };


    $.DrawChartForTable = function(table, chartIndex, chartDivId, options) {
        settings = $.extend({
            colors: ['red', 'green', 'blue', 'yellow', 'cyan', 'purple', 'orange', 'lime'],
            xAxisLabelsPlacement: "top"
        }, options);

        var eventSource = new Timeplot.DefaultEventSource();

        var timeGeometry = new Timeplot.DefaultTimeGeometry({
            gridColor: new Timeplot.Color("#000000"),
            axisLabelsPlacement: settings.xAxisLabelsPlacement
        });

        var valueGeometry = new Timeplot.DefaultValueGeometry({
            gridColor: new Timeplot.Color("#000000")//,
            //min: 0,
            //max: 100
        });

        var data = jQuery.GetVerticalDataFromTable(table);
        var lineCount = data[0].value.length;
        var plotInfo = new Array();
        $.ApplyVerticalLegendToTable(table, lineCount, settings.colors);

        for (var i = 0; i < lineCount; i++) {
            plotInfo[i] = Timeplot.createPlotInfo({
                id: 'plot' + i,
                dataSource: new Timeplot.ColumnSource(eventSource, i + 1),
                timeGeometry: timeGeometry,
                valueGeometry: valueGeometry,
                lineColor: settings.colors[(i) % (settings.colors.length)],
                dotColor: settings.colors[(i) % (settings.colors.length)],
                showValues: true
            });
        }

        timeplots[chartIndex] = Timeplot.create(document.getElementById(chartDivId), plotInfo);
        timeplots[chartIndex].loadArray(data, chartDivId, eventSource);
    };

    $.GetVerticalDataFromTable = function(table) {
        var data = new Array();
        $.each($(table).find('tbody').get(), function(bodyIndex) {
            $.each($(this).find('tr').get(), function(rowIndex) {
                var rowData = { date: null, value: new Array() };
                $.each($(this).find('th').get(), function(i) {
                    rowData.date = $(this).text();
                });
                $.each($(this).find('td').get(), function(i) {
                    rowData.value[i] = $(this).text();
                });
                data[rowIndex] = rowData;
            });
        });
        return data;
    };

    $.ApplyVerticalLegendToTable = function(table, columnCount, colors) {
        for (var i = 0; i < columnCount; i++) {
            $.each($(table).find('tr td:nth-child(' + (i + 2) + ')').get(), function(rowIndex) {
                $(this).addClass('border-' + colors[(i) % (colors.length)]);
            });
        }
    };

    $.ResizeChartsForWindow = function() {
        if (resizeTimerID == null) {
            resizeTimerID = window.setTimeout(function() {
                resizeTimerID = null;
                for (var i = 0; i < timeplots.length; i++) {
                    timeplots[i].repaint();
                }
            }, 100);
        }
    };

})(jQuery);

/* Timeplot globals *********************************************************************************/

var timeplots = new Array();
var resizeTimerID = null;

/* Timeplot loading extensions **********************************************************************/

/* Mimic the timeplot.loadText function */
Timeplot._Impl.prototype.loadArray = function(data, chartDivId, eventSource, filter) {
    if (this._active) {
        var tp = this;
        try {
            if (data.length > 0) { // added to check for empty result set
                eventSource.loadArray(data);
            }
            else {
                $('#' + chartDivId).empty().html("<span class='error'>No data found</span>");
            }
        } catch (e) {
            SimileAjax.Debug.exception(e);
        } finally {
            tp.hideLoadingMessage();
        }
    }
}

/* Mimic the eventSource.loadText function */
Timeplot.DefaultEventSource.prototype.loadArray = function(data, filter) {
    if (data == null) {
        return;
    }
    this._events.maxValues = new Array();

    var dateTimeFormat = 'iso8601';
    var parseDateTimeFunction = this._events.getUnit().getParser(dateTimeFormat);

    var added = false;

    if (filter) {
        data = filter(data);
    }

    if (data) {
        for (var i = 0; i < data.length; i++) {
            var row = data[i];
            if (row.date) {
                var evt = new Timeplot.DefaultEventSource.NumericEvent(
                    parseDateTimeFunction(row.date),
                    row.value
                );
                this._events.add(evt);
                added = true;
            }
        }
    }

    if (added) {
        this._fire('onAddMany', []);
    }
}